<%@ page import="com.party.core.model.system.TargetType" %>
<%@ page contentType="text/html;charset=UTF-8"%>
<%@ include file="../include/tag.jsp"%>
<!DOCTYPE html>
<html lang="zh">
<head>
    <title>${showGood == null ? '发布' : '编辑'}导购商品</title>
    <%@include file="../include/commonFile.jsp"%>
    <link rel="stylesheet" href="${ctx}/css/common/list.css">
    <link rel="stylesheet" href="${ctx}/css/ui/activity/publish_form.css">
</head><body>
<!--头部-->
<%@include file="../include/header.jsp"%>
<div class="index-outside">
    <%@include file="../include/sidebar.jsp"%>
    <!--内容-->
    <section>
        <div class="section-main">
            <!-- 正文请写在这里 -->
            <div class="add-form-content">
                <form id="myForm" class="layui-form mt20" method="post" action="${ctx}/mall/showgoods/save.do">
                    <input type="hidden" name="id" value="${showGood.id}" />
                    <input type="hidden" name="targetId" value="${showGood.targetId}" />
                    <input type="hidden" name="type" value="${showGood.type}" />
                    <input type="hidden" name="subjectId" value="${subjectId}" />
                    <input type="hidden" name="templateId" value="${templateId}" />
                    <div class="layui-form-item">
                        <label class="layui-form-label">商品名称<span class="f-verify-red">*</span></label>
                        <div class="layui-input-block">
                            <input type="text" name="name" lay-verify="name" autocomplete="off"
                                   placeholder="商品名称" class="layui-input" value="${showGood.name}"
                            >
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">商品连接<span class="f-verify-red">*</span></label>
                        <div class="layui-input-block">
                            <%--<input type="hidden" id="hiddenUrl" value=""/>--%>
                            <input type="hidden" id="urlType" value=""/>
                            <input type="text" name="url" id="url" autocomplete="off" lay-verify="url"
                                   placeholder="商品连接" class="layui-input" style="float: left; width: 900px" value="${showGood.url}"
                                   oninput="changeShowDiv()"
                            />
                            <a class="layui-btn layui-btn-danger" style="float: left; margin-left: 10px" id="chooseGoods"><i class="iconfont icon-add btn-icon"></i>选择链接</a>
                        </div>
                        <%--<div class="show-div">
                            <span class="show-name"></span>
                            <img class="show-goods" src=""/>
                        </div>--%>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">数量说明<span class="f-verify-red">*</span></label>
                        <div class="layui-input-inline">
                            <input type="text" name="numExplain" lay-verify="numExplain" autocomplete="off"
                                   placeholder="数量说明" class="layui-input" value="${showGood.numExplain}"
                            >
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <div class="layui-inline">
                            <label class="layui-form-label">商品类别<span class="f-verify-red">*</span></label>
                            <div class="layui-input-inline">
                                <select name="categoryId" id="categoryId" lay-verify="categoryId" lay-filter="categoryId">
                                	<option value="${category.id}" selected="selected">${category.name}</option>
                                </select>
                                <%-- <input type="text" name="category" id="category" class="layui-input" value="${category}" disabled="disabled" /> --%>
                            </div>
                        </div>
                    </div>

                    <div class="layui-form-item">
                        <label class="layui-form-label">图片<span class="f-verify-red">*</span></label>
                        <div class="cover-content">
                            <input type="hidden" name="pic" id="pic" lay-verify="pic" value="${showGood.pic}" />
                            <c:if test="${showGood == null || empty showGood.pic}">
                                <span id="cover-img" class="cover-img" style="background-image:url(${ctx}/image/posterImg.png)"></span>
                            </c:if>
                            <c:if test="${showGood != null && not empty showGood.pic}">
                                <span id="cover-img" class="cover-img" style="background-image:url('${showGood.pic}')"></span>
                            </c:if>
                            <a class="layui-btn layui-btn-danger" id="sel_pic_img">+添加图片</a>

                            <div class="form-word-aux">建议尺寸：800x800</div>
                        </div>
                    </div>
                    <div class="layui-form-item">
                        <label class="layui-form-label">商品描述</label>
                        <div class="layui-input-block">
                            <input type="text" name="remarks" placeholder="商品描述" class="layui-input" value="${showGood.remarks}">
                        </div>
                    </div>
                    
                    <div class="layui-form-item">
                        <div class="layui-input-block">
                            <a href="javascript:void(0)" class="layui-btn layui-btn-danger" lay-submit lay-filter="*">立即提交</a>
                            <c:if test="${!empty subjectId}">
                                <a href="${ctx}/mall/showgoods/list.do?subjectId=${subjectId}&categoryId=${categoryId}" class="layui-btn layui-btn-primary">取消</a>
                            </c:if>
                            <c:if test="${!empty templateId}">
                                <a href="${ctx}/mall/showtemplategoods/list.do?templateId=${templateId}&categoryId=${categoryId}" class="layui-btn layui-btn-primary">取消</a>
                            </c:if>
                        </div>
                    </div>
                </form>
            </div>
        </div><!--底部-->
        <%@include file="../include/footer.jsp"%>
    </section>
</div>
<script type="text/javascript" src="${ctx}/script/common/form_cache.js"></script>
<script>
    var form,formcache;
    $(function() {
        layui.use([ 'form', 'laydate' ], function() {
            form = layui.form, laydate = layui.laydate;

            //自定义验证规则
            form.verify({
                name : function(value) {
                    if (value == "" || !value.trim()) {
                        return '商品名不能为空';
                    }
                },
                url : function(value) {
                    if (value == "" || !value.trim()) {
                        return "连接不能为空";
                    }
                },
                numExplain: function (value) {
                    if (value == "" || !value.trim()){
                        return "数量说明不能为空";
                    }
                },
                categoryId : function(value) {
                    if (value == "" || !value.trim()) {
                        return "请选择类型";
                    }
                },
                pic : function(value) {
                    if (value == "" || !value.trim()) {
                        return "图片不能为空";
                    }
                }
            });

            //监听提交
            form.on('submit', function (data) {
                var targetId = $('[name=targetId]').val() || '';
                var type = $('[name=type]').val() || '';

                var result = true;
                if (util.isValid(targetId) && util.isValid(type)) {
                    ajaxSubmit({
                        'showCategoryId': '${categoryId}',
                        'targetId': targetId,
                        'type': type,
                        'showGoodsId': '${showGood.id}'
                    }, '${ctx}/mall/showgoods/checkTarget.do', function (data) {
                        result = data;
                    });
                }
                if (result) {
                    submitForm(data);
                } else {
                    util.layerMsgError("当前类型下已存在，请重新选择");
                }
            });

            function ajaxSubmit(data, url, cb) {
                $.ajax({
                    type: 'get',
                    async: false, // 使用同步的方法
                    data: data,
                    dataType: 'json',
                    success: function (result) {
                        typeof cb === 'function' && cb(result);
                    },
                    url: url
                });
            }

            function submitForm(data) {
                txz.submitObject(data.elem, function (callBack) {
                    var formData = getFormData();
                    var action = $("#myForm").attr("action");
                    txz.ajaxRequest({
                        method: 'post',
                        url: action,
                        saveCache: false,
                        cacheObj: formcache,
                        params: formData,
                        callBack: function (res) {
                            typeof callBack === 'function' && callBack();
                            if (res.success) {
                                util.layerMsgSuccess("提交成功", function () {
                                    if (util.isValid('${subjectId}')) {
                                        location.href = "${ctx}/mall/showgoods/list.do?subjectId=${subjectId}&categoryId=${categoryId}";
                                    }
                                    if (util.isValid('${templateId}')) {
                                        location.href = "${ctx}/mall/showtemplategoods/list.do?templateId=${templateId}&categoryId=${categoryId}";
                                    }
                                });
                            } else {
                                util.layerMsgError("提交失败")
                            }
                        }
                    })
                });
            }
        });
        $('#sel_pic_img').click(function () {
            txz.openSelImg({
                min: 1,
                max: 1,
                info: '建议尺寸：800x800',
                type: '<%=TargetType.MALL.getCode()%>',
                cb: function (imgs) {
                    $('#cover-img').css('background-image', 'url(' + imgs[0].path + ')');
                    $('#pic').val(imgs[0].path);
                }
            })
        })
        //等待ueditor加载完后加载缓存
        <%--if(!'${showGood.id}'){--%>
            <%--formcache = new fCache({--%>
                <%--fCacheKey: 'form_cache_goods',//暂存的key--%>
                <%--cacheCallback: loadCacheData,//获取到缓存后加载的方法--%>
                <%--getFormData: getFormData--%>
            <%--}).init();--%>
        <%--}--%>
    })



    //此方法用于加载缓存数据
    function loadCacheData(cacheData) {
        //加载封面图
        if (cacheData['pic']) {
            $('#cover-img').css('background-image', 'url(' + cacheData['pic'] + ')');
        }
        form.render();
    }

    function getFormData() {
        return util.serializeForm($('#myForm').serializeArray());
    }

    /*var isChoose = false;

    function changeShowDiv() {
        if (isChoose) {
            $('.show-div').css('display', 'none');
            isChoose = false;
        }
    }*/
    
    // 选择链接
    $('#chooseGoods').click(function () {
        openDialog('选择商品或分类', '${ctx}/mall/goods/selectGoods.do', '', '650px', '570px', function ($jquery) {
            var datas = $($jquery.find("#selectDatas")).val();
            var _result = (eval(datas))[0];

            $("[name=targetId]").val(_result.targetId);

            var targetType = _result.type;
            if (_result.type == 2) { // 商品
                targetType = 2;
            } else if (_result.type == 3) { // 分类
                targetType = 1;
            }
            $("[name=type]").val(targetType);


            /*isChoose = true;*/

            // 图片回显
            /*var showName = '';
            if (_result.type == 2) {
                showName = '商品名: ';
            } else if (_result.type == 3) {
                showName = '分类名: ';
            }
            $('.show-div .show-goods').attr('src', _result.pic);
            $('.show-div .show-name').text(showName + _result.name);
            $('.show-div').css('display', 'block');*/

            $('[name=name]').val(_result.name);
            $('#cover-img').css('background-image', 'url(' + _result.pic + ')');
            $('#pic').val(_result.pic);

            // 获取路径
            txz.ajaxRequest({
                method: 'post',
                url: '${ctx}/mall/showtemplategoods/getUrl.do',
                params: _result,
                callBack: function (res) {
                    if (res.success) {
                        var url = res.data;
                        if (url.indexOf("http:") < 0 && url.indexOf("https:") < 0) {
                            url = "http:" + url;
                        }
                        $('#url').val(url);
                        /*$('#hiddenUrl').val(res.data);*/
                    } else {

                    }
                }
            });
            $('#urlType').val(_result.type);
        });
    });

    function openDialog(title, url, content, width, height, cb, target) {
        var index = layer.open({
            type: url ? 2 : 1,
            area: [width, height],
            title: title,
            maxmin: true, //开启最大化最小化按钮
            content: url || $(content),
            btn: ['确定', '关闭'],
            yes: function (index, layero) {
                if (content) {
                    cb(index);
                }
                if (url) {
                    var body = layer.getChildFrame('body', index);
                    var iframeWin = layero.find('iframe')[0]; //得到iframe页的窗口对象，执行iframe页的方法：iframeWin.method();
                    var inputForm = body.find('#inputForm');
                    var top_iframe;
                    if (target) {
                        top_iframe = target;//如果指定了iframe，则在改frame中跳转
                    } else {
                        top_iframe = '_parent';//获取当前active的tab的iframe
                    }
                    inputForm.attr("target", top_iframe);//表单提交成功后，从服务器返回的url在当前tab中展示

                    if (iframeWin.contentWindow.doSubmit()) {
                        cb(iframeWin.contentWindow.$);

                        setTimeout(function () {
                            top.layer.close(index);
                        }, 100);//延时0.1秒，对应360 7.1版本bug
                    }
                }
            },
            cancel: function (index) {
            }
        });
    }
</script>
<script type="text/javascript">
    txz.initHeader({
        <c:if test="${!empty subjectId}">
        nav:[{
            name: '导购主题',
            href:'${ctx}/mall/showsubject/list.do'
        },{
            name: '类型管理',
            href: '${ctx}/mall/showcategory/list.do?subjectId=${subjectId}'
        },{
            name: '商品导购',
            href: '${ctx}/mall/showgoods/list.do?subjectId=${subjectId}&categoryId=${categoryId}'
        },{
            name: '${showGood == null ? '发布' : '编辑'}导购商品',
            curr: true
        }],
        btns:[{
            type: 'back'
        }]
        </c:if>
        <c:if test="${!empty templateId}">
        nav:[{
            name: '主题分类',
            href:'${ctx}/mall/showtemplate/list.do'
        },{
            name: '类型管理',
            href: '${ctx}/mall/showtemplatecategory/list.do?templateId=${templateId}'
        },{
            name: '商品导购',
            href: '${ctx}/mall/showtemplategoods/list.do?templateId=${templateId}&categoryId=${categoryId}'
        },{
            name: '${showGood == null ? '发布' : '编辑'}导购商品',
            curr: true
        }],
        btns:[{
            type: 'back'
        }]
        </c:if>
    });
</script>
</body>
</html>